package com.smxy.daydayup.util.osa;

import com.smxy.daydayup.pojo.User;
import com.smxy.daydayup.util.JwtUtils;
import com.smxy.daydayup.util.TenantContext;
import com.smxy.daydayup.util.result.ResultUtil;
import com.smxy.daydayup.util.result.ReturnResult;
import com.smxy.daydayup.util.result.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: yusy
 * @Date: 2022/8/12
 */
@RestController
@Api(tags = "对象存储上传")
@RequestMapping("/api/osa/")
public class OSAUploadController {

    @Autowired(required = false)
    OSAProvider osaProvider;

    @ApiOperation(value = "上传文件")
    @PostMapping(value = "upload")
    public ReturnResult<ObjectStorageInfo> upload(
            HttpServletRequest request,
            @RequestParam(value = "file") MultipartFile file, @RequestParam(required = false, name = "bucket") String bucket, @RequestParam(required = false, name = "path") String path) {
        if (osaProvider == null) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"系统未配置存储策略");
        }
        User userInfoByToken = JwtUtils.getUserInfoByToken(request);
        if (userInfoByToken == null) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"未登录");
        }
        TenantContext.init(new TenantContext.Tenant(userInfoByToken.getUserId(), userInfoByToken.getUserName()));
        final ObjectStorageInfo res = osaProvider.upload(file, new OSAProvider.CustomeInfo(bucket, path));
        return ResultUtil.returnSuccess(res, "");
    }

}
